﻿#include "DataStroes.h"
#include "StoreFilePath.h"
#include "utils/Logger/Logger.h"
#include "utils/Time/Time.h"
#include "components/FWidgets/Base/FTheme.h"

#include <QDebug>
#include <QApplication>
#include <QTranslator>
#include <QLocale>
#include <QFontDatabase>

// 注意：该类不可使用初始化参数列表初始化，必须先创建好目录后再初始化类成员！
DataStroes::DataStroes(QObject *parent)
    : QObject{parent}
{
    // 创建目录
    StoreFilePath::mkdirs();

    m_tlvPrj = new TlvProject(this);
    m_settings = new AppSettings(this);
    m_releaseNotes = new ReleaseNotes(this);
}

DataStroes::~DataStroes()
{

}

DataStroes *DataStroes::instance()
{
    static DataStroes* inst = nullptr;
    if (!inst) {
        inst = new DataStroes();
    }
    return inst;
}

void DataStroes::loadStores()
{
    // 初始化日志系统
    QString logFile = QString("%1/%2.log").arg(StoreFilePath::logDir(), Time::getYMD());
    Logger::instance().init(logFile);

    // 检查是否有文件参数传入
    bool canOpenArg = false;
    QStringList args = qApp->arguments();
    if (args.count() > 1) {
        QString filePath = args.at(1);
        if (filePath.endsWith(TLVPRJ_EXT, Qt::CaseInsensitive)) {
            if (QFile(filePath).exists()) {
                m_tlvPrj->open(filePath);
                canOpenArg = true;
            }
        }
    }
    // 加载上一次打开的项目
    if (!canOpenArg) {
        m_tlvPrj->open(m_tlvPrj->latestProject());
    }

    // 初始化APP设置
    m_settings->loadSettings();

    // 加载翻译
    QString language = m_settings->model().data().general.language;
    if (language.isEmpty()) {  // 未设置语言则使用操作系统当前语言
        language = QLocale::system().name();
    }
    QTranslator* translator = new QTranslator(this);
    if (translator->load(QString(":/tr/TlvTool_%1").arg(language))) {
        qApp->installTranslator(translator);
    }

    // 加载 release notes
    m_releaseNotes->loadNotes();

    // 加载资源
    loadResources();

    // 样式表
    qApp->setStyleSheet(FTheme::fstylesheet());
}

TlvProject *DataStroes::tlvPrj() const
{
    return m_tlvPrj;
}

AppSettings *DataStroes::settings() const
{
    return m_settings;
}

ReleaseNotes *DataStroes::releaseNotes() const
{
    return m_releaseNotes;
}

void DataStroes::loadResources()
{
    QFontDatabase::addApplicationFont(":/fonts/CASCADIAMONO.TTF");
}
